import { TodoStore } from '../stores/todo.store'
import * as uuid from 'node-uuid'
import { computed, observable, reaction } from 'mobx'
import { nonenumerable } from 'nonenumerable'

export class Todo {
  id = null
  @observable completed = false
  @observable task = ''
  @observable authorId = null

  get author() {
    return null
  }

  @nonenumerable
  private store = null
  @nonenumerable
  private autoSave = true
  @nonenumerable
  private saveHandler = null

  @computed get asJson() {
    return JSON.stringify(this)
  }

  constructor(store: TodoStore, id = uuid.v4()) {
    this.store = store
    this.id = id

    this.saveHandler = reaction(
      () => this.asJson,
      (json) => {
        if (this.autoSave) {
          this.store.transportLayer.saveTodo(json)
        }
      }
    )
  }

  delete() {
    this.store.transportLayer.deleteTodo(this.id)
    this.store.removeTodo(this)
  }

  updateFromJson({ completed, task, authorId }) {
    this.autoSave = false
    this.completed = completed
    this.task = task
    this.authorId = authorId
    this.autoSave = true
  }

  dispose() {
    this.saveHandler()
  }
}
